from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QResizeEvent
from PySide6.QtWidgets import QFrame, QVBoxLayout
from qfluentwidgets import StateToolTip, TitleLabel, PushButton, InfoBar, TransparentToolButton, FluentIcon
from components import LineEditFrame, OpenFileDialog
from common import MergeToExcelThread
from ..base import ReturnView


class ReLineEdit(LineEditFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.openFileButton.setText('选择文件')

    def openFileEvent(self):
        file = OpenFileDialog(self).getSaveFileName('./merge.xlsx', filter='Excel文件(*.xlsx;*.xls)')[0]
        self.lineEdit.setText(file)


class MergeExcelView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.stateToolTip = StateToolTip('Excel文件合成', '正在合成Excel文件，请稍后...', parent=self)
        self.stateToolTip.hide()
        self.initUI()
        self.initEvent()
        self.initLayout()

    def initUI(self):
        self.titleLabel = TitleLabel(self)
        self.titleLabel.setText('Excel合并')
        self.lineEdit = LineEditFrame(self)
        self.lineEdit.setFixedHeight(35)
        self.lineEdit.bodyLabel.setFixedSize(120, 30)
        self.lineEdit.setLabelText('选择Excel文件夹：')

        self.lineEdit_2 = ReLineEdit(self)
        self.lineEdit_2.setFixedHeight(35)
        self.lineEdit_2.bodyLabel.setFixedSize(120, 30)
        self.lineEdit_2.setLabelText('选择保存文件：')

        self.startButton = PushButton()
        self.startButton.setText('开始')

        self.merge_thread = MergeToExcelThread(self)

    def initEvent(self):
        self.returnButton.clicked.connect(self.returned.emit)
        self.startButton.clicked.connect(self.start_event)
        self.merge_thread.started.connect(self.started_thread)
        self.merge_thread.error.connect(lambda msg: InfoBar.error('错误', msg, duration=5000, parent=self))
        self.merge_thread.finished.connect(self.finished_thread)

    def initLayout(self):
        self.vBox.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignHCenter)
        self.vBox.addWidget(self.lineEdit)
        self.vBox.addWidget(self.lineEdit_2)
        self.vBox.addWidget(self.startButton)

    def resizeEvent(self, event: QResizeEvent):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)

    def started_thread(self):
        self.stateToolTip.show()

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('成功', '转换成功', duration=3000, parent=self)

    def start_event(self):
        dir_file = self.lineEdit.lineEditText()
        save_file = self.lineEdit_2.lineEditText()
        if dir_file == '' or save_file == '':
            InfoBar.warning('提示', '请选择路径信息', duration=2000, parent=self)
            return

        self.merge_thread.set_value(dir_file, save_file)
        self.merge_thread.start()
